package com.example.ndktest;

import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Arrays;

public class OrderActivity extends AppCompatActivity {

    // 需要排序的数组
    private int[] orderArrays = {6, 2, 5, 9, 1, 3, 4, 7, 8, 0, 10};

    private TextView tvResult;
    private Button btnOrder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order);

        EventBus.getDefault().register(this);

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setTitle("实战：数组排序");
        }

        tvResult = findViewById(R.id.tv_result);
        setResultText(orderArrays);

        btnOrder = findViewById(R.id.btn_order);
        btnOrder.setOnClickListener(view -> {
            // 调用本地排序方法，根据是否有异常打印success/failed
            boolean isSuccess = JNIHelper.doSort(orderArrays);
            btnOrder.setText(isSuccess ? "SUCCESS" : "FAILED");
        });
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            this.finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void setResultText(int[] array) {
        tvResult.setText(Arrays.toString(array));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateResult(int[] array) {
        tvResult.setText(Arrays.toString(array));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
